<template>
  <div class="table-page lf">
    <div class="flex flex-wrap">
      <ms-data-card title="订单量" :value="Number(amount?.total ?? 0)"></ms-data-card>
      <ms-data-card title="GMV" :value="Number(amount?.gmv ?? 0)" :precision="2"></ms-data-card>
      <ms-data-card title="服务费" :value="Number(amount?.totalCommission ?? 0)" :precision="2"></ms-data-card>
    </div>
    <a-form :model="listParams" size="small" class="form w-full flex flex-wrap">
      <!-- <a-form-item hide-label class="w-42n mr-10">
        <a-select
          class="w-42n"
          v-model="listParams.platformId"
          placeholder="选择平台类型检索"
          @change="changeCurrent(1)"
        >
          <a-option value="" label="全部"></a-option>
          <a-option v-for="item in platformList" :key="item.id" :value="item.id" :label="item.title"></a-option>
        </a-select>
      </a-form-item> -->
      <!-- <a-form-item hide-label class="w-42n mr-10">
        <a-select class="w-42n" v-model="listParams.isSyncUser" placeholder="选择是否已同步" @change="changeCurrent(1)">
          <a-option value="" label="全部"></a-option>
          <a-option :value="1" label="已同步"></a-option>
          <a-option :value="0" label="未同步"></a-option>
        </a-select>
      </a-form-item> -->
      <a-form-item hide-label class="w-42n mr-10">
        <a-select
          class="w-42n"
          v-model="listParams.orderStatus"
          placeholder="选择订单状态检索"
          @change="changeCurrent(1)"
        >
          <a-option :value="0" label="全部"></a-option>
          <a-option :value="1" label="已付款"></a-option>
          <a-option :value="10" label="已失效"></a-option>
          <a-option :value="2" label="已结算"></a-option>
          <a-option :value="20" label="违规订单"></a-option>
        </a-select>
      </a-form-item>
      <a-form-item hide-label class="w-fit mr-10">
        <a-input-group class="flex w-full">
          <a-select class="w-36n" v-model="key2">
            <a-option value="orderSn" label="订单号"></a-option>
            <a-option value="tradeId" label="子订单号"></a-option>
            <a-option value="goodsSign" label="商品ID"></a-option>
          </a-select>
          <a-input class="w-36n" v-model="value2" @press-enter="changeCurrent(1)" placeholder="请输入" />
        </a-input-group>
      </a-form-item>
      <a-form-item label="支付时间" class="w-100n mr-10">
        <ms-date
          v-model:start="listParams.startTime"
          v-model:end="listParams.endTime"
          :showQuick="true"
          @dateChange="changeCurrent(1)"
        ></ms-date>
      </a-form-item>
      <a-form-item label="结算时间" class="w-100n mr-10">
        <ms-date
          v-model:start="listParams.startFinishTime"
          v-model:end="listParams.endFinishTime"
          :showQuick="true"
          @dateChange="changeCurrent(1)"
        ></ms-date>
      </a-form-item>
      <a-form-item hide-label class="w-fit">
        <a-button type="primary" size="small" @click="changeCurrent(1)">
          <template #icon>
            <icon-search />
          </template>
          <template #default>查询</template>
        </a-button>
        <a-button class="ml-m" size="small" @click="onResetSearch">
          <template #icon>
            <icon-sync />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-form-item>
    </a-form>
    <GiTable
      row-key="tradeId"
      id="orderJdTeamList1"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      @refresh="getTableData"
    >
      <!-- <template #custom-extra>
        <div class="flex flex-a-c">
          <span class="mr-m">当前拦截状态:</span>
          <a-switch
            checked-text="开启中"
            unchecked-text="未开启"
            v-model="timeOpen"
            :before-change="handleChangeStatus"
          ></a-switch>
          <a-button type="primary" size="mini" class="ml-m" @click="openTimeList">
            <template #icon>
              <icon-question-circle />
            </template>
            过往拦截时间查看
          </a-button>
        </div>
      </template> -->
      <template #info="{ record }">
        <div class="flex">
          <a-image width="100" height="100" class="mr-10 cursor-pointer" :src="record.order.goodsInfo.imageUrl" />
          <div class="flex-col m-relative flex-1 overflow-hidden">
            <div style="min-height: 22px" class="my-2 line-h-24 text-overflow-2">
              <div class="m-absolute t-0 l-0" v-if="record.sourceTypeName">
                <a-tag color="red">{{ record.sourceTypeName }}</a-tag>
              </div>
              <div
                :style="{
                  textIndent: `${record.sourceTypeName ? record.sourceTypeName.length * 14 + 18 : 0}px`
                }"
              >
                <a-tooltip :content="record.order.skuName">
                  <span>{{ record.order.skuName }}</span>
                </a-tooltip>
              </div>
            </div>
            <div class="flex flex-a-c text-size-13 text808080 my-2" v-if="record.order.goodsInfo.shopName">
              <img src="@/assets/images/dianpu.png" alt="" class="mr-2 w-4n h-4n" />
              <span class="text-overflow-1 flex-1">{{ record.order.goodsInfo.shopName }}</span>
            </div>
            <div class="text-size-12 flex flex-a-c">
              <ms-copy-div showLeftTitle :text="record.order.itemId" title="商品ID"></ms-copy-div>
            </div>
          </div>
        </div>
      </template>
      <template #order="{ record }">
        <div class="w-full flex-col">
          <ms-copy-div showLeftTitle :text="record.orderSn" title="订单号"></ms-copy-div>
          <ms-copy-div showLeftTitle :text="record.tradeId" title="子订单号"></ms-copy-div>
          <div>订单状态：{{ record.orderStatusName }}</div>
        </div>
      </template>
      <template #time="{ record }">
        <div class="w-full flex-col flex-j-c">
          <div>下单时间: {{ record.paidTime || '--' }}</div>
        </div>
      </template>
      <template #commission="{ record }">
        <div class="w-full flex-col">
          <div class="flex flex-a-c my-2" v-if="record.payPrice">
            支付金额:<span class="textd43030 text-size-14 font-bold">￥{{ record.payPrice }} </span>
          </div>
          <div>预估服务费: ¥ {{ record.commission }}</div>
          <div>服务费率: {{ record.commissionRate }}%</div>
        </div>
      </template>
      <template #isSyncUser="{ record }">
        <a-tag :color="record.isSyncUser == 1 ? '#00b42a' : '#f53f3f'">{{
          record.isSyncUser == 1 ? '已同步' : '未同步'
        }}</a-tag>
      </template>
      <template #action="{ record }">
        <template v-if="record.isSyncUser == 1">
          <span>--</span>
        </template>
        <template v-else>
          <a-button type="text" size="small" @click="onSync(record.id)"> 同步给会员 </a-button>
        </template>
      </template>
    </GiTable>
  </div>
</template>

<script setup>
import { Message, Modal } from '@arco-design/web-vue'
import { usePagination, useLayer } from '@/hooks'
import Time from './Time.vue'
import {
  orderJdTeamList,
  cloudCrossOrderSyncUser,
  cloudCrossOrderEnableStatus,
  cloudCrossOrderEnableSetting,
  goodsDetailWithB,
  orderJdTeamOrder
} from '@/apis'
import { usePlatform } from '@/hooks/app'
import { deepClone, deleteEmpty, reAssign } from '@/utils/common'

defineOptions({ name: 'orderJdTeam' })
const columns = ref([
  {
    title: '商品信息',
    slotName: 'info',
    width: 330
  },
  {
    title: '订单信息',
    slotName: 'order',
    width: 250
  },
  {
    title: '时间',
    slotName: 'time',
    width: 250
  },
  {
    title: '服务费',
    slotName: 'commission',
    width: 200
  }
  // {
  //   title: '是否同步',
  //   slotName: 'isSyncUser',
  //   width: 120
  // },
  // {
  //   title: '操作',
  //   slotName: 'action',
  //   width: 120
  // }
])

const loading = ref(false)
const tableData = ref([])
const key2 = ref('orderSn')
const value2 = ref('')
const timeOpen = ref(false)

const { platformList, getPlatformList, formatPlatform } = usePlatform()
getPlatformList()

const amount = reactive({
  gmv: 0,
  total: 0,
  totalCommission: 0
})

const listParams = reactive({
  page: 1,
  size: 10,
  startTime: undefined,
  endTime: undefined,
  startFinishTime: undefined,
  endFinishTime: undefined,
  platformId: 2,
  orderStatus: undefined,
  isSyncUser: undefined
})

const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: listParams.size })

// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    listParams.size = pagination.pageSize
    const param = deepClone(listParams)
    if (key2.value === 'goodsSign' && value2.value) {
      const r = await goodsDetailWithB({ platformId: listParams.platformId, goodsId: value2.value })
      if (JSON.stringify(r.data) != '[]') {
        param[key2.value] = r.data.jdGoodsIdB
      } else param[key2.value] = value2.value
    } else {
      param[key2.value] = value2.value
    }
    getCloudCrossOrderEnableStatus()
    const res = await orderJdTeamList(deleteEmpty(param))
    tableData.value = res.data.data.map((item) => {
      return { ...item, sourceTypeName: formatPlatform(item.platformId) }
    })
    const amountRes = await orderJdTeamOrder(deleteEmpty(param))
    reAssign(amount, amountRes?.data ?? {})
    setTotal(res?.data?.total || 0)
  } finally {
    loading.value = false
  }
}

const getCloudCrossOrderEnableStatus = async () => {
  const res = await cloudCrossOrderEnableStatus()
  timeOpen.value = JSON.stringify(res.data) === '[]' ? false : true
}

onMounted(() => {
  getTableData()
})

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

// 重置筛选查询
const onResetSearch = () => {
  // listParams.platformId =
  listParams.orderStatus =
    listParams.isSyncUser =
    listParams.startTime =
    listParams.endTime =
    listParams.startFinishTime =
    listParams.endFinishTime =
      undefined
  key2.value = 'orderSn'
  value2.value = ''
  changeCurrent(1)
}

// 同步操作
const onSync = (id) => {
  Modal.warning({
    title: '提示',
    content: '确认要同步给会员吗？',
    hideCancel: false,
    closable: true,
    onOk: async () => {
      await cloudCrossOrderSyncUser({ id })
      Message.success('操作成功')
      getTableData()
    }
  })
}

// 改变同步状态
const handleChangeStatus = async () => {
  await new Promise((resolve, reject) => {
    cloudCrossOrderEnableSetting()
      .then(() => {
        Message.success('操作成功')
        getCloudCrossOrderEnableStatus()
        resolve(true)
      })
      .catch(() => {
        reject()
      })
  })
}

// 打开时间列表
const openTimeList = () => {
  useLayer().openLayer(
    Time,
    {
      title: `云跨店订单开启拦截时间列表`,
      area: ['700px', '500px']
    },
    getCloudCrossOrderEnableStatus
  )
}
</script>

<style lang="scss" scoped>
.textd90000 {
  color: #d90000;
}
.aggs {
  width: fit-content;
  line-height: 26px;
  background-color: rgb(var(--primary-1));
  box-shadow: rgb(var(--primary-1)) solid 1px;
  border-radius: 4px;
  border: 1px solid $color-theme;
}
.text808080 {
  color: #808080;
}
.text-size-13 {
  font-size: 13px;
}
.textd43030 {
  color: #d43030;
}
.text2a82e4 {
  color: #2a82e4;
}
</style>
